import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput } from "react-native";
import { GLOBAL } from '../../../config/global';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { RangTime } from '../../../component/common/RangTime.js';
import MethodUtil from '../../../utils/MethodUtil';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const calendar = require('../../../imgs/calendar.png');
const TAB_LIST = [
  {
    name: '销项票',
    id: 2, // TODO
    count: 0,
  }, {
    name: '进项票',
    id: 1, // TODO
    count: 0,
  }
]

export class BillListPage extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      headerTitle: '结算发票列表',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props);
    const { choice } = props.navigation.state.params || {};
    this.state = {
      status: 'loading',
      showTimeModal: false, // 时间选择
      refreshIcon: false, // 下拉刷新图标
      listData: [], // 列表数据
      saleCount: 0,
      purchaseCount: 0,
      startDate: null,
      endDate: null,
      alertShow: false,
      options: [],
      choice: choice || {}
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.totalPage = 1; // 总页数

    this.pageParams = { // TODO
      companyType: this.props.navigation.state.params.tabIndex ? this.props.navigation.state.params.tabIndex : 2,  // 1:供应商---进项   2:客户---销项
      selectedName: '销项票',
      searchKey: this.props.navigation.state.params.companyName || '',
      startDate: this.props.navigation.state.params.strtime ? this.props.navigation.state.params.strtime : null,
      endDate: this.props.navigation.state.params.endTime ? this.props.navigation.state.params.endTime : null,
      pageNo: 1,
      pageSize: 10
    }
  }

  async componentWillMount() {
    await this.fun_date(-30);
    await this.getSorage();
    await this.getRecord();
    await this.initPage();
  }

  //获取业务组织
  async getSorage() {
    const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    const userInfo = JSON.parse(userInfoJson);
    this.setState({
      options: userInfo.corpInfoTOs || [],
      choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
    })
  }

  //获取最近一周日期
  fun_date(num) {
    let date1 = new Date();
    //今天时间
    let time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
    let date2 = new Date(date1);
    date2.setDate(date1.getDate() + num);
    //num是正数表示之后的时间，num负数表示之前的时间，0表示今天
    let time2 = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
    this.pageParams.startDate = this.props.navigation.state.params.strtime ? this.props.navigation.state.params.strtime : time2;
    this.pageParams.endDate = this.props.navigation.state.params.endTime ? this.props.navigation.state.params.endTime : time1;
    this.setState({
      startDate: this.props.navigation.state.params.strtime ? this.props.navigation.state.params.strtime : time2,
      endDate: this.props.navigation.state.params.endTime ? this.props.navigation.state.params.endTime : time1,
    })
  }

  async initPage() {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    this.pageParams.corpId = this.state.choice.corpId;
    console.log('this.pageParams========>', this.pageParams)
    let res = await HTTP.POST(API_GENERATE(API.GET_INVOICE_LIST), this.pageParams); // TODO
    if (res) {
      this.totalPage = res.totalPage;
      this.setState({
        status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
        refreshIcon: false
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  // 获取列表数量
  async getRecord() {
    let params = {};
    params.searchKey = this.pageParams.searchKey;
    params.startDate = this.pageParams.startDate;
    params.endDate = this.pageParams.endDate;
    params.pageNo = this.pageParams.pageNo;
    params.pageSize = this.pageParams.pageSize;
    params.corpId = this.state.choice.corpId;
    params.companyType = 2;  // 1:供应商---进项   2:客户---销项
    const sale_res = await HTTP.POST(API_GENERATE(API.GET_INVOICE_LIST), params); // TODO
    params.companyType = 1;
    const purchase_res = await HTTP.POST(API_GENERATE(API.GET_INVOICE_LIST), params); // TODO
    this.setState({
      saleCount: sale_res.recordCount || 0,
      purchaseCount: purchase_res.recordCount || 0,
    })
  }

  // 刷新页面
  async  reloadPage() {
    this.pageParams.pageNo = 1;
    this.reload = true;
    await this.getRecord();
    await this.initPage();
  }

  // 下拉刷新
  async  refresh() {
    this.pageParams.pageNo = 1;
    this.reload = false;
    await this.getRecord();
    await this.initPage();
  }

  // 上拉翻页
  loadMore() {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initPage();
    }
  }

  // tab切换
  changeTab = async (item) => {
    this.pageParams.pageNo = 1;
    this.pageParams.companyType = item.id;
    this.pageParams.selectedName = item.name;
    await this.initPage();
  }

  // 选择时间
  _resultCall = (resultData) => {
    this.pageParams.startDate = resultData.startTime || '';
    this.pageParams.endDate = resultData.endTime || resultData.startTime;
    this.setState({
      showTimeModal: false,
      startDate: resultData.startTime || '',
      endDate: resultData.endTime || resultData.startTime,
    }, async () => {
      await this.getRecord();
      await this.initPage();
    })
  }

  // 日期和筛选
  _renderFilterWrap() {
    let { startDate, endDate } = this.state;
    return (
      <View style={styles.filterWrap}>
        <TouchableOpacity activeOpacity={.8} style={styles.dateWrap} onPress={() => {
          this.setState({ showTimeModal: true })
        }}>
          <View style={styles.dateImgWrap}>
            <Image source={calendar} style={{ width: 17 * scale, height: 14 * scale }} />
          </View>
          <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
            <Text style={styles.dateText}>{startDate || '开始时间'}</Text>
            <Text style={styles.dateLine}></Text>
            <Text style={styles.dateText}>{endDate || '结束时间'}</Text>
          </View>
        </TouchableOpacity>

        <View>
          <Image source={searchIcon} style={styles.searchIcon} />
          <TextInput
            ref="enterpriseInput"
            style={styles.searchInput}
            underlineColorAndroid='transparent'
            placeholder={"企业/结算单/发票/订单"}
            placeholderTextColor="rgba(255, 255, 255, .8)"
            maxLength={30}
            returnKeyType={'search'}
            defaultValue={this.pageParams.searchKey == '' ? this.pageParams.searchKey : this.pageParams.searchKey != '' ? this.pageParams.searchKey.length > 12 ? (this.pageParams.searchKey.substr(0, 11) + '...') : this.pageParams.searchKey :
              this.props.navigation.state.params.companyName.length > 12 ? (this.props.navigation.state.params.companyName.substr(0, 11) + '...') : this.props.navigation.state.params.companyName}
            onChangeText={(txt) => { this.pageParams.searchKey = txt }}
            onSubmitEditing={() => { this.reloadPage(); }}
          />
        </View>
      </View>
    )
  }

  // tab
  _renderTabWrap() {
    const { saleCount, purchaseCount } = this.state;
    return (
      <View style={styles.tabWrap}>
        {
          TAB_LIST.map((item, index) => {
            return (
              <TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(item) }} key={index} style={[styles.tabItem, this.pageParams.companyType == item.id ? null : { borderBottomColor: style.color.themeColor }]}>
                <Text style={[styles.tabText, this.pageParams.companyType == item.id ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name} {item.id == 2 ? saleCount : purchaseCount}</Text>
              </TouchableOpacity>
            )
          })
        }
      </View>
    )
  }

  // 列表
  _renderListItem = (data) => {
    const { invoiceId, invoiceNo, buyerName, sellerName, invocieDate, totalAmt } = data.item;
    return (
      <TouchableOpacity key={data.index} activeOpacity={1} onPress={() => {
        this.props.navigation.navigate('BillDetailPage', {
          title: this.pageParams.selectedName,
          companyType: this.pageParams.companyType,
          data: data.item,
          choice: this.state.choice,
        })
      }} style={{ marginBottom: 18 * scale }}>
        {/**进项票：显示收款方  销项票：显示付款方*/}
        <Text style={{ color: '#848A96', marginBottom: 6 * scale }}>
          {this.pageParams.companyType == 1 ? (sellerName || '-') : (buyerName || '-')}
        </Text>
        <View style={{ backgroundColor: '#fff', borderRadius: 4 * scale }}>
          <View style={styles.billNumWrap}>
            <Text style={styles.commonTitle}>发票号</Text>
            <Text style={styles.commonText}>{invoiceNo || '-'}</Text>
          </View>

          <View style={styles.billInfoWrap}>
            <View style={{ flexDirection: 'row', alignItems: 'center', width: '55%' }}>
              <Text style={styles.commonTitle}>开票日期</Text>
              <Text style={styles.commonText}>{(invocieDate || '-').substring(0, 10)}</Text>
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', width: '45%' }}>
              <Text style={[styles.commonTitle, { minWidth: 40 * scale }]}>金额</Text>
              <Text numberOfLines={1} style={[styles.commonText, { flex: 1 }]}>¥<Text style={{ fontSize: 16 * scale }} >{MethodUtil.toThousands(totalAmt, 2)}</Text></Text>
            </View>
          </View>
        </View>
      </TouchableOpacity>
    )
  }

  render() {
    let { status, showTimeModal, listData, refreshIcon, startDate, endDate, alertShow, choice, options } = this.state;
    return (
      <View style={styles.container}>
        {options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
        <View style={styles.headerWrap}>
          {this._renderFilterWrap()}

          {this._renderTabWrap()}
        </View>


        {
          status == 'data' ? (
            <View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale }}>
              <FlatList
                data={listData}
                style={{ marginLeft: 20 * scale, marginRight: 20 * scale }}
                renderItem={this._renderListItem}
                refreshing={refreshIcon}
                onRefresh={() => { this.refresh() }}
                onEndReachedThreshold={0.1}
                onEndReached={() => { this.loadMore() }}
              />
            </View>) : <PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />
        }

        {
          showTimeModal ? <RangTime isClear={true} isVisible={true} markedDates={null} startTime={startDate} endTime={endDate} closeCall={() => { this.setState({ showTimeModal: false }) }} resultCall={this._resultCall} /> : null
        }
        <SlideSelect alertShow={alertShow} options={options}
          select={(val) => {
            this.setState({ choice: val || options[0], alertShow: false }, () => {
              this.reloadPage();
            })
          }}
          unselect={() => {
            this.setState({ alertShow: false })
          }} />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  headerWrap: {
    backgroundColor: style.color.themeColor,
    paddingLeft: 17 * scale,
    paddingRight: 17 * scale,
  },
  filterWrap: {
    marginTop: 25 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    position: 'relative',
  },
  dateWrap: {
    width: 110 * scale,
    height: 36 * scale,
    paddingLeft: 36 * scale,
    borderRadius: 18 * scale,
    backgroundColor: 'rgba(255 ,255 , 255, .18)',
    flexDirection: 'row',
    justifyContent: 'center',
    paddingRight: 14 * scale,
  },
  dateImgWrap: {
    width: 36 * scale,
    height: 36 * scale,
    borderRadius: 18 * scale,
    backgroundColor: 'rgba(255, 255, 255, .08)',
    position: 'absolute',
    top: 0,
    left: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  dateText: {
    fontSize: 10 * scale,
    color: '#fff',
    opacity: .8,
    textAlign: 'center'
  },
  dateLine: {
    width: 7 * scale,
    height: 1 * scale,
    backgroundColor: 'rgba(255, 255, 255, .36)',
    marginTop: 3 * scale,
    marginBottom: 3 * scale,
  },
  searchInput: {
    height: 36 * scale,
    width: 220 * scale,
    paddingLeft: 42 * scale,
    paddingRight: 12 * scale,
    backgroundColor: 'rgba(255, 255, 255, .18)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 0,
    position: 'relative',
    borderRadius: 18 * scale,
    color: '#fff',
    fontSize: 13 * scale
  },
  searchIcon: {
    width: 20 * scale,
    height: 22 * scale,
    position: 'absolute',
    left: 12 * scale,
    top: 8 * scale,
    zIndex: 9,
    opacity: 0.8,
  },
  tabWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  tabItem: {
    borderBottomColor: '#fff',
    borderBottomWidth: 3 * scale,
    borderStyle: 'solid',
    paddingTop: 20 * scale,
    paddingBottom: 12 * scale,
    paddingLeft: 16 * scale,
    paddingRight: 16 * scale
  },
  tabText: {
    color: '#fff'
  },
  billNumWrap: {
    borderStyle: 'solid',
    borderBottomColor: '#E3E7F0',
    borderBottomWidth: 1 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 16 * scale,
    paddingRight: 16 * scale,
    height: 36 * scale
  },
  billInfoWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingLeft: 16 * scale,
    paddingRight: 16 * scale,
    height: 40 * scale,
  },
  commonTitle: {
    fontSize: 13 * scale,
    minWidth: 64 * scale
  },
  commonText: {
    fontSize: 13 * scale,
    fontWeight: '600',
  },
})